package cn.harry.cabinet.view

import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.cardview.widget.CardView
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.User
import cn.harry.cabinet.model.enums.UserStatus
import cn.harry.cabinet.repository.UserRepository
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 密码验证页面
 * 用户输入工号和密码进行验证
 */
class PasswordAuthActivity : BaseAuthActivity() {
    
    private lateinit var employeeIdInputLayout: TextInputLayout
    private lateinit var passwordInputLayout: TextInputLayout
    private lateinit var employeeIdInput: TextInputEditText
    private lateinit var passwordInput: TextInputEditText
    private lateinit var loginButton: CardView
    private lateinit var statusText: TextView
    private lateinit var userRepository: UserRepository
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_password_auth)
        
        // 初始化Repository
        userRepository = UserRepository(application)
        
        // 初始化视图
        initViews()
        
        // 应用主题
        applyTheme()
        
        // 设置点击事件
        setupClickListeners()
    }
    
    private fun initViews() {
        employeeIdInputLayout = findViewById(R.id.til_employee_id)
        passwordInputLayout = findViewById(R.id.til_password)
        employeeIdInput = findViewById(R.id.et_employee_id)
        passwordInput = findViewById(R.id.et_password)
        loginButton = findViewById(R.id.btn_login)
        statusText = findViewById(R.id.tv_status)
        
        // 更新标题
        val titleText = findViewById<TextView>(R.id.tv_title)
        titleText.text = getPageTitle("密码验证")
    }
    
    private fun setupClickListeners() {
        findViewById<ImageView>(R.id.btn_back)?.setOnClickListener {
            finish()
        }
        
        loginButton.setOnClickListener {
            performLogin()
        }
    }
    
    private fun performLogin() {
        val employeeId = employeeIdInput.text?.toString()?.trim()
        val password = passwordInput.text?.toString()?.trim()
        
        // 清除之前的错误
        employeeIdInputLayout.error = null
        passwordInputLayout.error = null
        
        // 验证工号
        if (employeeId.isNullOrEmpty()) {
            employeeIdInputLayout.error = "请输入工号"
            return
        }
        
        if (employeeId.length > 8) {
            employeeIdInputLayout.error = "工号最多8位"
            return
        }
        
        // 验证密码
        if (password.isNullOrEmpty()) {
            passwordInputLayout.error = "请输入密码"
            return
        }
        
        if (password.length != 4) {
            passwordInputLayout.error = "密码必须是4位"
            return
        }
        
        statusText.text = "正在验证..."
        loginButton.isEnabled = false
        
        lifecycleScope.launch {
            try {
                val user = withContext(Dispatchers.IO) {
                    userRepository.getUserByEmployeeId(employeeId)
                }
                
                withContext(Dispatchers.Main) {
                    if (user != null) {
                        // 检查用户状态
                        if (user.status != UserStatus.ENABLED) {
                            statusText.text = "用户已被禁用"
                            Toast.makeText(this@PasswordAuthActivity, "用户已被禁用", Toast.LENGTH_SHORT).show()
                            loginButton.isEnabled = true
                            return@withContext
                        }
                        
                        // 验证密码
                        if (password == user.password) {
                            onAuthSuccess(user)
                        } else {
                            statusText.text = "密码错误"
                            Toast.makeText(this@PasswordAuthActivity, "密码错误", Toast.LENGTH_SHORT).show()
                            loginButton.isEnabled = true
                        }
                    } else {
                        statusText.text = "工号不存在"
                        Toast.makeText(this@PasswordAuthActivity, "工号不存在", Toast.LENGTH_SHORT).show()
                        loginButton.isEnabled = true
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    statusText.text = "验证失败: ${e.message}"
                    Toast.makeText(this@PasswordAuthActivity, "验证失败", Toast.LENGTH_SHORT).show()
                    loginButton.isEnabled = true
                }
            }
        }
    }
    
    private fun onAuthSuccess(user: User) {
        Toast.makeText(this, "登录成功！欢迎 ${user.name}", Toast.LENGTH_SHORT).show()
        super.onAuthSuccess(user, "password")
    }
    
}
